package org.example.shardiing.config;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author linshiqiang
 * @date 2025-06-14 11:35:00
 * @description 时间 按年分片
 */
public class TimestampPreciseShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String getType() {
        return "PRECISE_TIME_BY_YEAR_ALGORITHM";
    }

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        Long timestamp = preciseShardingValue.getValue();
        timestamp = System.currentTimeMillis() ;
        int year = ShardingUtils.getYear(timestamp);
        return preciseShardingValue.getLogicTableName() + "_" + year;
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> rangeShardingValue) {
        Range<Long> valueRange = rangeShardingValue.getValueRange();
        int lowerYear = ShardingUtils.getYear(valueRange.lowerEndpoint());
        int upperYear = ShardingUtils.getYear(valueRange.upperEndpoint());
        List<String> tableNames = new ArrayList<>();
        String logicTableName = rangeShardingValue.getLogicTableName();
        for (int year = lowerYear; year <= upperYear; year++) {
            String tableName = logicTableName + "_" + year;
            if (availableTargetNames.contains(tableName)) {
                tableNames.add(tableName);
            }
        }
        return tableNames;
    }
}
